package com.billjc.activity.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * Druid数据源配置
 * 
 * @author bruce
 *
 */
@Configuration
public class DruidConfig {
	/**
	 * activity使用的数据源(默认为主数据源)
	 * 
	 * @return
	 */
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	@Primary
	public DataSource activityDataSource() {
		return new DruidDataSource();
	}
	/**
     * 外网数据源
     * @return
     */
	@ConfigurationProperties(prefix = "spring.platsysDataSource")
	@Bean(name="platsysDataSource")
	public DataSource platsysDataSource() {
		return new DruidDataSource();
	}
	
	@Bean(name = "platsysJdbcTemplate")
    public JdbcTemplate platsysJdbcTemplate(
            @Qualifier("platsysDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
	// 配置Druid的监控
	// 1、配置一个管理后台的Servlet
	@Bean
	public ServletRegistrationBean statViewServlet() {
		ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		Map<String, String> initParams = new HashMap<>();
		// 设置监控页面登录
		initParams.put("loginUsername", "billjc");
		initParams.put("loginPassword", "password");
		initParams.put("allow", "");// 默认就是允许所有访问
		bean.setInitParameters(initParams);
		return bean;
	}

	// 2、配置一个web监控的filter
	@Bean
	public FilterRegistrationBean webStatFilter() {
		FilterRegistrationBean bean = new FilterRegistrationBean();
		bean.setFilter(new WebStatFilter());

		Map<String, String> initParams = new HashMap<>();
		initParams.put("exclusions", "*.js,*.css,/druid/*");

		bean.setInitParameters(initParams);

		bean.setUrlPatterns(Arrays.asList("/*"));

		return bean;
	}
}
